/**
 * @fileOverview
 */

/**
 * @class
 */
Karamu = Karamu || {};
Karamu.Controllers = Karamu.Controllers || {};

/**
 * Groups are displayed as categories in desktop view; as tabs in dashboard view. Tabs are sub-divided into columns, and
 * gadgets are stacked in the columns.
 *
 * @class
 * @requires jQuery, underscore.js, karamu.js
 * @param {Object} context the top-level controller object, e.g karamu
 */
Karamu.Controllers.Gadget = function(context){
    this.context = context;

    this.render = function(gadgetData, index){
        if ($('#overlay').is(':visible')) {
            $('#overlay').hide();
        }

        var stagger = index * 20;
        if (stagger > $('#windows').height() - gadgetData.height || stagger > $('#windows').width() - gadgetData.width) {
            stagger = 0;
        }
        var gadgetLink = this.context.tmpl('desktop-gadget-button', {
            id: 'gadget-' + index,
            title: gadgetData.title
        });
        var gadget = this.context.tmpl('desktop-gadget', {
            id: 'gadget-' + index,
            title: gadgetData.title,
            style: 'position: absolute; left: ' + stagger + 'px; top: '+ stagger + 'px;'
        });

        gadgetLink.on({click: this.toggle}, this);

        $('.navbar', gadget).on({click: this.focus, dblclick: this.zoom}, this).css('cursor','move');
        $('.icon.maximize', gadget).on({click: this.zoom}, this);
        $('.icon.minimize', gadget).on({click: this.minimize}, this);
        $('.icon.remove', gadget).on({click: this.close}, this);

        this.unfocus();

        $('#dock').append(gadgetLink);
        $('#windows').append(gadget);

        var that = this;
        gadget
            .addClass('active')
            .height(gadgetData.height)
            .width(gadgetData.width)
            .draggable({
                handle: '.navbar',
                containment: $('#windows'),
                refreshPositions: true,
                start: function(e, ui){
                    $('.gadget-dimmer').show();
                },
                stop: function(e, ui){
                    $('.gadget-dimmer').hide();
                }
            })
            .resizable({
                autoHide: false,
                containment: $('#windows'),
                handles: 's, sw, se',
                helper: 'ui-resizable-helper',
                minHeight: 150,
                minWidth: 250,
                start: function(e, ui){
                    $('#windows .gadget:not(.active) .gadget-dimmer').show();
                },
                stop: function(e, ui){
                    $('#windows .gadget:not(.active) .gadget-dimmer').hide();
                    gadgets.pubsub2router.hub.publish('adjustHeight', {
                        gadget: ui.element,
                        height: ui.size.height - $('.navbar', ui.element).height()
                    });
                }
            });

        var shindigGadget = shindig.container.createGadget({
            specUrl: gadgetData.url,
            title: gadgetData.title,
            height: gadgetData.height,
            width: gadgetData.width,
            scrolling: true
        });
        shindig.container.addGadget(shindigGadget);
        shindigGadget.render($('.gadget-body', gadget)[0]);

        gadgets.pubsub2router.hub.publish('adjustHeight', {
            gadget: gadget,
            height: gadgetData.height
        });
    };

    this.getGadget = function(e){
        if        ($(e.currentTarget).is('a')) {
            return $($(e.currentTarget).attr('href'));
        } else if ($(e.currentTarget).is('li')) {
            return $($('a', e.currentTarget).attr('href'));
        } else if ($(e.currentTarget).is('.gadget')) {
            return $(e.currentTarget);
        } else {
            return $($(e.currentTarget).parents('.gadget')[0]);
        }
    };

    this.savePosition = function(e){
        e.preventDefault();
        var gadget = e.data.getGadget(e);

        gadget.attr({
            'data-t': gadget.css('top'),
            'data-l': gadget.css('left'),
            'data-r': gadget.css('right'),
            'data-b': gadget.css('bottom'),
            'data-w': gadget.css('width'),
            'data-h': gadget.css('height')
        });
    };

    this.unfocus = function(){
        $('#dock a').addClass('btn-inverse');
        $('#dock i').addClass('icon-white');
        $('#windows .gadget').removeClass('active');
    };

    this.focus = function(e){
        e.preventDefault();
        var gadget = e.data.getGadget(e),
            gadgetId = gadget.attr('id'),
            gadgetLink = $('#dock a[href="#' + gadgetId + '"]');

        e.data.unfocus();
        gadget.addClass('active');
        gadgetLink.removeClass('btn-inverse');
        $('i', gadgetLink).removeClass('icon-white');
        return false;
    };

    this.maximize = function(e) {
        e.preventDefault();
        var gadget = e.data.getGadget(e),
            gadgetId = gadget.attr('id'),
            gadgetLink = $('#dock a[href="#' + gadgetId + '"]');

        if (!gadget.hasClass('minimized')){
            e.data.savePosition(e);
        }
        gadget.animate({
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            width: '100%',
            height: '100%',
            opacity: 'show'
        }, 250, function(){
            e.data.unfocus();
            gadget.addClass('maximized active');
            gadgetLink.removeClass('btn-inverse').addClass('maximized');
            $('i', gadgetLink).removeClass('icon-white');
            gadgets.pubsub2router.hub.publish('adjustHeight', {
                gadget: gadget,
                height: gadget.height() - $('.navbar', gadget).height()
            });
        });
        return false;
    };

    this.minimize = function(e) {
        e.preventDefault();
        var gadget = e.data.getGadget(e),
            gadgetId = gadget.attr('id'),
            gadgetLink = $('#dock a[href="#' + gadgetId + '"]');

        if (!gadget.hasClass('maximized')) {
            e.data.savePosition(e);
        }
        gadget.animate({
            width: 'hide' ,
            height: 'hide',
            opacity: 'hide'
        }, 250, function(){
            e.data.unfocus();
            gadget.addClass('minimized active');
            gadgetLink.removeClass('btn-inverse').addClass('minimized');
            $('i', gadgetLink).removeClass('icon-white');
            gadgets.pubsub2router.hub.publish('adjustHeight', {
                gadget: gadget,
                height: gadget.height() - $('.navbar', gadget).height()
            });
        });
        return false;
    };

    this.normalize = function(e) {
        e.preventDefault();
        var gadget = e.data.getGadget(e),
            gadgetId = gadget.attr('id'),
            gadgetLink = $('#dock a[href="#' + gadgetId + '"]');

        gadget.animate({
            top: gadget.attr('data-t'),
            left: gadget.attr('data-l'),
            right: gadget.attr('data-r'),
            bottom: gadget.attr('data-b'),
            width: gadget.attr('data-w'),
            height: gadget.attr('data-h'),
            opacity: 'show'
        }, 250, function(){
            e.data.unfocus();
            gadget.removeClass('maximized minimized').addClass('active');
            gadgetLink.removeClass('maximized minimized btn-inverse');
            $('i', gadgetLink).removeClass('icon-white');
            gadgets.pubsub2router.hub.publish('adjustHeight', {
                gadget: gadget,
                height: gadget.height() - $('.navbar', gadget).height()
            });
        });
        return false;
    };

    this.toggle = function(e){
        e.preventDefault();
        var gadget = e.data.getGadget(e),
            gadgetId = gadget.attr('id'),
            gadgetLink = $('#dock a[href="#' + gadgetId + '"]');

        if (gadget.hasClass('minimized') && gadget.hasClass('maximized')) {
            e.data.maximize(e);
        } else if (gadget.hasClass('minimized')) {
            e.data.normalize(e);
        } else {
            e.data.unfocus();
            gadget.addClass('active');
            gadgetLink.removeClass('btn-inverse');
            $('i', gadgetLink).removeClass('icon-white');
        }
        return false;
    };

    this.zoom = function(e){
        e.preventDefault();
        var gadget = e.data.getGadget(e),
            gadgetId = gadget.attr('id'),
            gadgetLink = $('#dock a[href="#' + gadgetId + '"]');

        if (!gadget.hasClass('maximized')) {
            e.data.maximize(e);
        } else {
            e.data.normalize(e);
        }
        return false;
    };

    this.close = function(e){
        e.preventDefault();
        var gadget = e.data.getGadget(e),
            gadgetId = gadget.attr('id'),
            gadgetLink = $('#dock a[href="#' + gadgetId + '"]');

        gadget.animate({
            width: 'hide' ,
            height: 'hide',
            opacity: 'hide'
        }, 250, function(){
            gadgetLink.remove();
            gadget.remove();
        });
        return false;
    };

};